package com.scs.application.config;

import com.alibaba.fastjson.JSON;
import com.scs.application.core.aliyun.annotation.EnableAliyunSms;
import com.scs.application.core.msg.domain.SceneMessage;
import com.scs.application.modules.msg.handler.MessageQueue;
import com.scs.application.modules.msg.handler.SceneMessageHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Scheduled;

/**
 * @Description:
 */
@Slf4j
@Configuration
@EnableAliyunSms
public class SceneMessageConfig {

    @Autowired
    private SceneMessageHandler sceneMessageHandler;

    // 每五分钟执行一次 0 0/5 * * * ?
    @Scheduled(cron = "0 0/5 * * * ?")
    public void sendSceneMessage() {
        SceneMessage message = null;
        try {
            SceneMessage[] array = MessageQueue.array();
            int len = array.length;
            if (len > MessageQueue.onceSend) {
                len = MessageQueue.onceSend;
            }
            for (int i = 0; i < len; i++) {
                message = array[i];
                try {
                    sceneMessageHandler.handle(message);
                    //正常成功 remove
                    MessageQueue.remove(message);
                } catch (Exception e) {
                    log.error("场景消息处理失败，消息内容：" + JSON.toJSONString(message), e);
                    // write something
                    //重新入队
                    MessageQueue.remove(message);
                    MessageQueue.put(message);
                }
            }

        } catch (Exception e) {
            log.error("场景消息处理失败，", e);
        }
    }

}
